package com.robot.orders.service;

import com.robot.orders.dao.PurchaseDao;
import com.robot.orders.pojo.Purchase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * purchase服务层
 *
 * @author lin
 */
@Service
public class PurchaseService {
    @Autowired
    private PurchaseDao purchaseDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Purchase> findAll() {
        return purchaseDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Purchase> findSearch(Map whereMap, int page, int size) {
        Specification<Purchase> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return purchaseDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Purchase> findSearch(Map whereMap) {
        Specification<Purchase> specification = createSpecification(whereMap);
        return purchaseDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Purchase findById(String id) {
        return purchaseDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param purchase
     */
    public void add(Purchase purchase) {
        //雪花分布式ID生成器
        purchase.setId(idWorker.nextId() + "");
        LocalDateTime now = LocalDateTime.now();
        purchase.setCreatedAt(now);
        purchase.setUpdatedAt(now);
        purchase.setStatus("0");
        purchaseDao.save(purchase);
    }

    /**
     * 修改
     *
     * @param purchase
     */
    public void update(Purchase purchase) {
        purchaseDao.save(purchase);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        purchaseDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Purchase> createSpecification(Map searchMap) {
        return new Specification<Purchase>() {
            @Override
            public Predicate toPredicate(Root<Purchase> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 采购单id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 公司id
                String companyId = "companyId";
                if (searchMap.get(companyId) != null && !"".equals(searchMap.get(companyId))) {
                    predicateList.add(cb.like(root.get(companyId).as(String.class), "%" + (String) searchMap.get(companyId) + "%"));
                }
                // 店铺id
                String storeId = "storeId";
                if (searchMap.get(storeId) != null && !"".equals(searchMap.get(storeId))) {
                    predicateList.add(cb.like(root.get(storeId).as(String.class), "%" + (String) searchMap.get(storeId) + "%"));
                }
                // 店铺名字
                String storeName = "storeName";
                if (searchMap.get(storeName) != null && !"".equals(searchMap.get(storeName))) {
                    predicateList.add(cb.like(root.get(storeName).as(String.class), "%" + (String) searchMap.get(storeName) + "%"));
                }
                // 代理商id
                String agentId = "agentId";
                if (searchMap.get(agentId) != null && !"".equals(searchMap.get(agentId))) {
                    predicateList.add(cb.like(root.get(agentId).as(String.class), "%" + (String) searchMap.get(agentId) + "%"));
                }
                // 代理商姓名
                String agentName = "agentName";
                if (searchMap.get(agentName) != null && !"".equals(searchMap.get(agentName))) {
                    predicateList.add(cb.like(root.get(agentName).as(String.class), "%" + (String) searchMap.get(agentName) + "%"));
                }
                // 代理商手机号
                String agentPhone = "agentPhone";
                if (searchMap.get(agentPhone) != null && !"".equals(searchMap.get(agentPhone))) {
                    predicateList.add(cb.like(root.get(agentPhone).as(String.class), "%" + (String) searchMap.get(agentPhone) + "%"));
                }
                // 区县
                String area = "area";
                if (searchMap.get(area) != null && !"".equals(searchMap.get(area))) {
                    predicateList.add(cb.like(root.get(area).as(String.class), "%" + (String) searchMap.get(area) + "%"));
                }
                // 0-未使用 1-使用中 2-已用完
                String status = "status";
                if (searchMap.get(status) != null && !"".equals(searchMap.get(status))) {
                    predicateList.add(cb.like(root.get(status).as(String.class), "%" + (String) searchMap.get(status) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(Date.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * 通过agentId查询purchase列表并分页
     *
     * @param agentId
     * @param page
     * @param size
     * @return
     */
    public Page<Purchase> findAllByAgentIdAndDeletedAtIsNullOrderByCreatedAtDesc(String agentId, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return purchaseDao.findAllByAgentIdAndDeletedAtIsNullOrderByCreatedAtDesc(agentId, pageable);

    }

    /**
     * 通过agentId和status查询purchase列表并分页
     *
     * @param agentId
     * @param status
     * @param page
     * @param size
     * @return
     */
    public Page<Purchase> findAllByAgentIdAndStatusAndDeletedAtIsNullOrderByCreatedAtDesc(String agentId, String status, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return purchaseDao.findAllByAgentIdAndStatusAndDeletedAtIsNullOrderByCreatedAtDesc(agentId, status, pageable);
    }

    /**
     * 通过agentId,storeId,status查询purchase列表,按createdAt正序输出
     *
     * @param agentId
     * @param status
     * @return
     */
    public List<Purchase> findAllByAgentIdAndStoreIdAndStatusOrderByCreatedAt(String agentId, String storeId, String status) {
        return purchaseDao.findAllByAgentIdAndStoreIdAndStatusOrderByCreatedAt(agentId, storeId, status);
    }

    /**
     * 通过agentId和id查询purchase详情
     *
     * @param id
     * @param agentId
     * @return
     */
    public Purchase findByIdAndAgentId(String id, String agentId) {
        return purchaseDao.findByIdAndAgentId(id, agentId);
    }


    /**
     * 通过storeId查询purchase列表并分页
     *
     * @param storeId
     * @param page
     * @param size
     * @return
     */
    public Page<Purchase> findAllByStoreIdAndDeletedAtIsNullOrderByCreatedAtDesc(String storeId, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return purchaseDao.findAllByStoreIdAndDeletedAtIsNullOrderByCreatedAtDesc(storeId, pageable);

    }

    /**
     * 通过storeId和status查询purchase列表并分页
     *
     * @param storeId
     * @param status
     * @param page
     * @param size
     * @return
     */
    public Page<Purchase> findAllByStoreIdAndStatusAndDeletedAtIsNullOrderByCreatedAtDesc(String storeId, String status, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return purchaseDao.findAllByStoreIdAndStatusAndDeletedAtIsNullOrderByCreatedAtDesc(storeId, status, pageable);
    }

    /**
     * 通过storeId和id查询purchase详情
     *
     * @param id
     * @param storeId
     * @return
     */
    public Purchase findByIdAndStoreId(String id, String storeId) {
        return purchaseDao.findByIdAndStoreId(id, storeId);
    }

    /**
     * 通过agentId和storeId查找余额
     *
     * @param agentId
     * @param status
     * @return
     */
    public BigDecimal findPurchaseBalanceByAgentIdAndStoreId(String agentId, String status) {
        BigDecimal result = purchaseDao.findPurchaseBalanceByAgentIdAndStoreId(agentId, status);
        if (result == null) {
            result = new BigDecimal(0);
        }
        return result;
    }


    /**
     * 根据storeId查找剩余余额
     *
     * @param storeId
     * @return
     */
    public String findBalanceByStoreId(String storeId) {
        return purchaseDao.findBalanceByStoreId(storeId);
    }
}
